package com.sogoodsoft.util;

import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import com.sogoodsoft.entity.account.SecurityUser;
import com.sogoodsoft.entity.account.User;

public class InfosysSecurityUtil {
	private static Log log = LogFactory.getLog(InfosysSecurityUtil.class);
	
	/**	管理员权限标志，有此权限的用户，作为管理员 */
	private static String adminAuthFlag = "系统管理";
	
	public static String getCurrentRealName() {
		String realName = "匿名用户";
		User user= getCurrentUser();
		if(user!=null){realName = user.getName();}
		return realName;
	}
	
	public static User getCurrentUser(){
		User user = null;
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(!obj.getClass().equals(String.class)){
			SecurityUser sUser = (SecurityUser)obj;
			user = sUser.getUser();
		}else{
			log.debug("currUser is not a User Object:"+obj);
		}
		
		return user;
	}
	
	/**
	 * 判断是否拥有XXX权限
	 * @param auth
	 * @return
	 */
	public static boolean hasAuthority(String auth){
		boolean has = false;
		Collection<GrantedAuthority> col = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
		for(GrantedAuthority authority:col){
			//log.debug(authority.getAuthority()+"\t\tROLE_"+auth);
			if(authority.getAuthority().equals("ROLE_"+auth)){
				has = true;
			}
		}
		return has;
	}
	
	public static boolean isAdmin(){
		return hasAuthority(adminAuthFlag);
	}
	
	
}
